import Dom from '../utils/Dom';
import Events from '../utils/Events';
import ContextMenu from '../ui/ContextMenu';
import Tooltip from '../ui/Tooltip';
import Http from '../utils/Http';
import Config from '../config';
import Modal from "../ui/Modal";
import Utils from "../utils";

class Header {
   constructor(parent) {
      this.el = Dom.append(parent, 'div', 'header');
      this.init();

      // 监听状态变更，并更新对应的按钮状态
      Events.on('statusChange', (key, ...args) => {
         // console.log(key, args);
         if (key === 'dataUpdate') {
            // 启用保存
            this.disabledItem('system', 'save', !args[0]);
         } else if (key === 'nodeSelect') {
            // 启用或禁用作业组
            this.disabledItem('castSchedule','unscheduleCast', !args[0]);
         }
      });
   }

   init() {
        let mainMenuArray = Config.ifShowView ? 'showMenu' : 'mainMenu';
      this.buttons = Config[mainMenuArray];

      this.buttons.forEach((button, i) => {
         let ul = Dom.append(this.el, 'ul'),
            li = null;

         ul.index = i;
         if (button.disabled) {
            ul.className = 'disabled';
         }

         button.btns.forEach((btn, j) => {
            li = Dom.append(ul, 'li', null, '<img src="images/' + btn.icon + '.png" class="icon">' + btn.name);

            li.index = j;
            if (btn.sub) {
               li.className = 'btn-sub';
            }

            if (btn.disabled) {
               li.className += ' disabled';
            }

            if (btn.active) {
               li.className += ' active';
            }
         });

         button.ul = ul;
      });


      Dom.addEvent(this.el, 'click', e => {
         let target = e.target;
         // console.log(target)
         // return
         if (target.tagName === 'UL' || target.tagName === 'DIV') {
            return false;
         }
         while (true) {
            if (target.tagName === 'LI') {
               console.log(target)
               // 干扰事件
               if (target.id === 'raodongButton') {
                  Events.emit('raodongAction');
                  return
               }
               if (target.parentNode.index === undefined) {
                  return false;
               }
               let ulIndex = target.parentNode.index,
                  liIndex = target.index,
                  btn = this.buttons[ulIndex].btns[liIndex],
                  type = this.buttons[ulIndex].type;

               if (type === 'select') {
                  if (target.className && target.className.indexOf(' active') !== -1) {
                     return false;
                  }
                  this.buttons[ulIndex].ul.childNodes.forEach(li => {
                     if (li.className && li.className.indexOf('active') !== -1) {
                        li.className = li.className.replace(' active', '');
                     }
                  });

                  target.className += ' active';
               }

               if (btn.sub) {
                  let pos = Dom.pos(target, true),
                     size = Dom.size(target),
                     contextmenu = this[btn.icon + 'ContextMenu'];

                  if (!contextmenu) {
                     contextmenu = this[btn.icon + 'ContextMenu'] = new ContextMenu(btn.sub, index => {
                        console.log(btn.icon, btn.sub[index].code);
                        Events.emit('btnClick', btn.icon, btn.sub[index].code);
                        contextmenu.show(null, true);
                     });

                     contextmenu.root.style.left = pos.x + 'px';
                     contextmenu.root.style.top = pos.y + size.h + 10 + 'px';
                  }

                  contextmenu.show(e, null, true);



               } else if (btn.eventKey) {
                  Events.emit('btnClick', btn.eventKey);
               } else if (btn.click) {
                  btn.click();
               }
               return false;
            } else if (target.tagName === 'UL' || target.tagName === 'DIV') {
               return false;
            } else {
               target = target.parentNode
            }
         }
      });
      this.renderIron();
      this.raodong();
   }
   raodong(){
      this.raodongContainer = Dom.append(this.el, 'ul', 'raodong-container');
      this.raodongContainer.innerHTML = '<li id="raodongButton"><img src="images/chart.raodong.png" class="icon"/>干扰事件</li>'
   }
   // // 干扰事件
   // raodongAction(){
   //    Http.post(Config.api.raodong, null, res => {
   //       console.log(res)
   //       let dom1
   //       let modal = new Modal('干扰事件', body => {
   //          dom1 = Dom.append(body, 'div');
   //          dom1.style.width = '100%';
   //          dom1.style['max-height'] = '500px'
   //          dom1.style.overflow = 'auto'
   //          let innerHtml = '<table><thead><tr><th>id</th><th>事件内容</th><th>是否已确认</th><th>炉次/焦次号</th><th>事件发生时间</th></tr></thead>';
   //          for(let i = 0; i <res.length ;i++){
   //             innerHtml += '<tr><td>'+res[i].chargeId+'</td><td>'+res[i].rdType+'</td><td>'+res[i].chargeId+'</td><td>'+res[i].facilityNo+'</td><td>'+res[i].createdDt+'</td></tr>';
   //          }
   //          innerHtml += '</table>'
   //          dom1.innerHTML = innerHtml
   //       }, isOK => {}, {
   //          type: 'alert',
   //          className: 'modal-large'
   //       });
   //    })
   // }
   renderIron() {
      if (!this.ironContainer) {
         this.ironContainer = Dom.append(this.el, 'ul', 'iron-container');
         Dom.addEvent(this.ironContainer, 'mousemove', e => {
            let target = null;
            if (e.target.tagName === 'LI') {
               target = e.target;
            } else if (e.target.tagName === 'P' || e.target.tagName === 'IMG') {
               target = e.target.parentNode;
            }

            this.showIronTooltip(target);
            return Dom.nodefault(e);
         });

         Dom.addEvent(this.ironContainer, 'mouseout', e => {
            this.showIronTooltip();
            return Dom.nodefault(e);
         })
      }

      let html = '';
      Http.get(Config.api.findIronInfo, null, data => {
         if (data && data.length) {
            this.ironData = data;
            this.ironTooltipIndex = null;
            data.forEach((d, index) => {
               html += `<li data-index="${index}"><p>${d.ladleId}</p><img src="images/tiebao.png"><p>${d.devCode}</p></li>`;
            });
            this.ironContainer.innerHTML = html;
         }
      });
   }

   showIronTooltip(target) {
      if (!target) {
         if (this.ironTooltip)
            this.ironTooltip.hide();
         return false;
      }

      let index = parseInt(target.getAttribute('data-index')),
         data = this.ironData[index];

      if (this.ironTooltipIndex === index) {
         this.ironTooltip.show();
         return false;
      }

      if (!this.ironTooltip) {
         this.ironTooltip = new Tooltip({
            className: 'iron-tooltip'
         });
      }

      this.ironTooltip.show();

      if (!data.html) {
         let itmes = [{
            name: '脱硫站号',
            key: 'devCode'
         }, {
            name: '脱硫处理号',
            key: 'pretreatmentId'
         }, {
            name: '铁水重量',
            key: 'ironWeight'
         }, {
            name: '铁水出站温度',
            key: 'finishTemp'
         }, {
            name: '铁水进站时刻',
            key: 'moltenIronInTmstmp'
         }, {
            name: '铁水出站时刻',
            key: 'moltenIronOutTmstmp'
         }],
            elements = [{
               code: 'C',
               name: '碳'
            }, {
               code: 'Si',
               name: '硅'
            }, {
               code: 'Mn',
               name: '锰'
            }, {
               code: 'P',
               name: '磷'
            }, {
               code: 'S',
               name: '硫'
            }, {
               code: 'Ti',
               name: '钛'
            }, {
               code: 'V',
               name: '钒'
            }],
            html = '',
            key = null;

         itmes.forEach(item => {
            html += '<p><b>' + item.name + '：</b>' + (data[item.key] || '') + '</p>';
         });

         elements.forEach(el => {
            key = el.code.toLowerCase();
            html += '<p class="dcz"><b>进站-' + el.code + '：</b><span>' + (data[key + 'Dz'] || '') + '</span><b>出站-' + el.code + '：</b><span>' +
               (data[key + 'Cz'] || '') + '</span></p>';
         });

         data.html = html;
      }


      this.ironTooltip.show(data.html);

      if (!data.position) {
         let pos = Dom.pos(target, true),
            size = Dom.size(target),
            tSize = Dom.size(this.ironTooltip.root),
            position = {
               x: pos.x + size.w / 2 - tSize.w / 2,
               y: pos.y + size.h + 10
            };

         if (position.x + tSize.w > document.body.clientWidth) {
            position.x = document.body.clientWidth - tSize.w - 12;
         }

         data.position = position;
      }

      this.ironTooltip.setPosition(data.position);

      this.ironTooltipIndex = index;
   }

   disabledGroup(groupName, flag) {
      let group = null,
         i = 0,
         total = this.buttons.length,
         newClass = flag === undefined ? null : (flag ? 'disabled' : '');
      for (; i < total; i++) {
         if (this.buttons[i].group === groupName) {
            group = this.buttons[i];
            break;
         }
      }

      if (group) {
         if (group.ul.className === newClass) {
            return false;
         }

         if (newClass === null) {
            newClass = group.ul.className ? '' : 'disabled';
         }

         group.ul.className = newClass;

      }
   }

   disabledItem(groupName, btnId, flag) {
      let group = null,
         i = 0,
         total = this.buttons.length,
         btn = null,
         newClass = flag === undefined ? null : (flag ? 'disabled' : '');
      for (; i < total; i++) {
         if (this.buttons[i].group === groupName) {
            group = this.buttons[i];
            break;
         }
      }

      if (group) {
         i = 0;
         total = group.btns.length;
         for (; i < total; i++) {
            if (group.btns[i].id && group.btns[i].id === btnId) {
               btn = group.ul.childNodes[i];
               break;
            }
         }

         if (btn) {
            if (btn.className === newClass) {
               return false;
            }

            if (newClass === null) {
               newClass = btn.className ? '' : 'disabled';
            }
            btn.className = newClass;
         }
      }
   }
}

export default Header;
